package com.irdstudio.efp.esb.api.rest.sx;


import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import com.irdstudio.basic.framework.core.constant.CertTypeConstant;
import com.irdstudio.cdp.pboc.service.facade.BdZxInfoService;
import com.irdstudio.cdp.pboc.service.vo.BdZxInfoVO;
import com.irdstudio.efp.esb.common.constant.InstitutionEnums;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.constant.CountryConstant;
import com.irdstudio.basic.framework.core.constant.CurrencyConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.DateTool;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.irdstudio.basic.framework.core.util.MessageRuleCheckUtil;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TraceUtil;
import com.irdstudio.basic.framework.core.util.ValidationUtils;
import com.irdstudio.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.irdstudio.efp.basic.framework.mq.constant.TagEnums;
import com.irdstudio.efp.basic.framework.mq.constant.TopicEnums;
import com.irdstudio.efp.console.service.facade.PrdInfoService;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.esb.api.bean.sx.ReqCreditBean;
import com.irdstudio.efp.esb.api.bean.sx.RespCreditBean;
import com.irdstudio.efp.esb.api.common.AmtUtil;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.SDicServerConstant;
import com.irdstudio.efp.esb.api.common.GroupeInterface.bd;
import com.irdstudio.efp.esb.api.util.SDicMappingServer;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.MsLoanConstant;
import com.irdstudio.efp.esb.common.constant.nls.NlsProdCdEnum;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.limit.common.LimitConstant;
import com.irdstudio.efp.nls.common.constant.PrdAdaptedSoltEnums;
import com.irdstudio.efp.nls.common.constant.QueueTaskEnums;
import com.irdstudio.efp.nls.service.facade.queue.NlsProcessBizService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;

/**
 * 网贷授信进件申请
 *
 * @author heyingfeng
 * @version 1.0
 * @since 2019年3月4日 下午2:52:38
 */
@RestController
@RequestMapping("/esb")
public class NlsCreditBDController {
    private static Logger logger = LoggerFactory.getLogger(NlsCreditBDController.class);
    // 单位转换
    private final int oneHundred_100 = 100;
    private static final String MYD_TRN_DAY_30 = "30";
    private static final String ZXD_TRN_DAY_7 = "7";

    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午1:28:08
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午1:31:14
     */
    @ModelAttribute("reqCreditBean")
    public ReqCreditBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqCreditBean.class);
    }

    /**
     * 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息<br>
     * 2.调用对应的中台服务<br>
     * 3.增加调用队列任务表信息<br>
     * 此处为统一的进件交易，先暂时不按照产品代码进行划分，后续根据差异化需求决定是否拆分；
     *
     * @param esbReqServiceBean ESB请求对象
     * @param br1
     * @param reqCreditBean     ESB请求体的对象
     * @param br2
     * @param exception         切面的异常信息
     * @return
     * @throws Exception
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午2:20:51
     */
    @PostMapping("/SERVICE_30220001_03_05")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated({bd.class}) @ModelAttribute("reqCreditBean") ReqCreditBean reqCreditBean, BindingResult br2, Exception exception) throws Exception {
        String applSeq = reqCreditBean.getCrdtAppFlowNo();
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        TraceUtil.setTraceId(glblSrlNo);
        logger.info("授信申请交易开始----------申请流水号：" + applSeq + "------------全局流水号" + glblSrlNo);
        try {
            // 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息
            if (Objects.nonNull(exception)) {
                throw exception;
            }
            if (StringUtil.isEmpty(reqCreditBean.getEqlAmtPrin12Int()) && NlsProdCdEnum.MYD.getValue().equals(reqCreditBean.getProdCd())) {
                throw new BizException("等额本金12期利息EqlAmtPrin12Int  may not to null");
            } else {
                if (NlsProdCdEnum.MYD.getValue().equals(reqCreditBean.getProdCd())) {
                    MessageRuleCheckUtil.checkDouble(reqCreditBean.getEqlAmtPrin12Int(), "等额本金12期利息");
                }
            }
            if (StringUtil.isNotEmpty(reqCreditBean.getLoanAplLmt())) {
                MessageRuleCheckUtil.checkDouble(reqCreditBean.getLoanAplLmt(), "授信金额");
            }
            MessageRuleCheckUtil.checkInteger(reqCreditBean.getBDIdCertScr(), "百度身份证评分");
            MessageRuleCheckUtil.checkInteger(reqCreditBean.getBDAcctNoScr(), "百度账号评分");
            MessageRuleCheckUtil.checkInteger(reqCreditBean.getBDMblNoScr(), "百度手机号评分");
            if (StringUtil.isNotEmpty(reqCreditBean.getTxnTmstmp())) {
                MessageRuleCheckUtil.checkNumeric(reqCreditBean.getTxnTmstmp(), "交易时间戳");
            }
            if (StringUtil.isNotEmpty(reqCreditBean.getCertNo())) {
                MessageRuleCheckUtil.validateIdNo18(reqCreditBean.getCertNo());
            }

            // 2.获取业务逻辑字段
            String cusName = reqCreditBean.getBrwNm();
            String certType = StringUtil.isNullorBank(reqCreditBean.getCertTp()) ? CertTypeConstant.CODE_10100 : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.CERT_TYPE, reqCreditBean.getCertTp());
            String certNo = reqCreditBean.getCertNo();
            String mobile = reqCreditBean.getMblNo();
            String prdCde = reqCreditBean.getProdCd();
            String prdName = reqCreditBean.getLoanProdNm();
            String chanNo = reqCreditBean.getChanNo();
            String bdReqSn = reqCreditBean.getRepeatRqsBss();
            String bankCardNo = reqCreditBean.getBankCardNo();
            BigDecimal loanAmt = new BigDecimal(reqCreditBean.getLoanAplLmt());
            String loanTermType = StringUtil.isNullorBank(reqCreditBean.getTrmType()) ? BaseConstant.TERM_TYPE_DAY : reqCreditBean.getTrmType();
            // 交易时间转换
            long txnTmstmp = 0;
            if (StringUtil.isNotEmpty(reqCreditBean.getTxnTmstmp())) {
                txnTmstmp = Long.parseLong(reqCreditBean.getTxnTmstmp());
            }
            String aplDt = DateTool.formateDate(new Date(txnTmstmp), DateTool.PATTERN_DEFAULT);
            NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setLmtApplySeq(applSeq);
            nlsCreditInfoVO.setBdReqSn(bdReqSn);
            //根据流水号以及百度reqSn判断，流水号是数据表主键，不重复，reqSn是百度保持不重复 TODO
            nlsCreditInfoVO = nlsCreditInfoService.queryCopy(nlsCreditInfoVO);
            if (nlsCreditInfoVO != null) {
                return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
                        JSON.toJSONString(buildRespCreditBean(EsbBizEnums.RetCodeEnum.KHXXJYBTG.getVALUE(),
                                "授信申请流水号：" + "【" + applSeq + "】" + "，已经存在授信申请记录，请核查！")), //
                        EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
                        EsbBizEnums.RetCodeEnum.KHXXJYBTG.getVALUE(), //
                        "授信申请流水号：" + "【" + applSeq + "】" + "，已经存在授信申请记录，请核查！");
            }
            // 根据产品代码查询产品id
            PrdInfoVO vo = new PrdInfoVO();
            vo.setPrdCode(prdCde);
            PrdInfoVO outputVo = prdInfoService.queryLastPrdInfo(vo);
            if (outputVo == null || "".equals(outputVo.getPrdId())) {
                throw new BizException("无产品id");
            }
            prdName = outputVo.getPrdName();

            // 产品只能存在一笔授信，可以存在多个产品

            NlsCreditInfoVO checkVo = new NlsCreditInfoVO();
            //审批中 01
            checkVo.setApprvSts(MsLoanConstant.NlsApplyStateEnum.APPR.VALUE);
            checkVo.setCertType(reqCreditBean.getCertTp());
            checkVo.setCertCode(reqCreditBean.getCertNo());
            checkVo.setPrdCode(reqCreditBean.getProdCd());
            checkVo = nlsCreditInfoService.queryCopy(checkVo);
            if (checkVo != null) {
                return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
                        JSON.toJSONString(buildRespCreditBean(EsbBizEnums.RetCodeEnum.KHXXJYBTG.getVALUE(),
                                "该客户：" + "【" + reqCreditBean.getCertNo() + "】" + "，该产品已经存在处理中授信申请！")), //
                        EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
                        EsbBizEnums.RetCodeEnum.KHXXJYBTG.getVALUE(), //
                        "该客户：" + "【" + reqCreditBean.getCertNo() + "】" + "，该产品已经存在处理中授信申请！");
            }
           /* *//**单一产品重复申请判断 modify by chenxuan *//*
            checkVo.setApprvSts(MsLoanConstant.NlsApplyStateEnum.PASS.VALUE);
            checkVo = nlsCreditInfoService.queryCopy(checkVo);
            if (checkVo != null) {
                checkVo.setApprvSts(MsLoanConstant.NlsApplyStateEnum.REVOKED.VALUE);
                nlsCreditInfoService.updateByPk(checkVo);
            }
*/
            boolean flag = ValidationUtils.validPhoneNum("0", mobile);// 手机号
            if (flag == false) {
                throw new BizException("手机号错误");
            }
            // 3.验证客户是否存在
            // 根据身份证获取客户号
            String cusId = cusIndivService.getCusIdByCertCode(certType, certNo);
            cusId = StringUtil.isNullorBank(cusId) ? "" : cusId;

            // 额度类型
            String LmtType = "";
            if (NlsProdCdEnum.MYD.getValue().equals(prdCde)) {
                LmtType = LimitConstant.CRD_LMT_TYPE_10;
            } else if (NlsProdCdEnum.ZXD.getValue().equals(prdCde)) {
                LmtType = LimitConstant.CRD_LMT_TYPE_20;
            }
            // 4.调用中台服务
            // 插入授信申请基本信息表
            nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setLmtApplySeq(applSeq);// 流水号
            nlsCreditInfoVO.setBdReqSn(reqCreditBean.getRepeatRqsBss());// 请求方需要保证永远唯一响应方据此判断是否重复请求
            nlsCreditInfoVO.setBdTransactionId(reqCreditBean.getEvID());// 事务ID，贯穿 授信、用信
            nlsCreditInfoVO.setCusId(cusId);// 客户id
            nlsCreditInfoVO.setCusName(cusName);// 姓名+
            nlsCreditInfoVO.setCertType(certType);// 证件类型
            nlsCreditInfoVO.setCertCode(certNo);// 证件号码
            nlsCreditInfoVO.setLmtType(LmtType);//额度类型
            nlsCreditInfoVO.setCyclicFlg(outputVo.getCyclicWay());//是否循环
            nlsCreditInfoVO.setRecvAccount(bankCardNo);// 银行卡号
            nlsCreditInfoVO.setPrdId(outputVo.getPrdId());// 产品id
            nlsCreditInfoVO.setPrdCode(prdCde);// 产品代码
            nlsCreditInfoVO.setPrdName(prdName);// 产品名称
            nlsCreditInfoVO.setApplyAmt(loanAmt);// 申请金额
            nlsCreditInfoVO.setApproveAmt(loanAmt);// 审批金额
            if (NlsProdCdEnum.MYD.getValue().equals(prdCde)) {
                nlsCreditInfoVO.setApplyTerm(MYD_TRN_DAY_30);// 申请期限
            } else if (NlsProdCdEnum.ZXD.getValue().equals(prdCde)) {
                nlsCreditInfoVO.setApplyTerm(ZXD_TRN_DAY_7);// 申请期限
            }
            nlsCreditInfoVO.setTermType(loanTermType);// 期限类型
            nlsCreditInfoVO.setAssureMeansMain(BaseConstant.ASSURE_MEANS_00);// 担保方式
            nlsCreditInfoVO.setRepaymentMode(StringUtil.isNullorBank(outputVo.getRepayWay()) ? "" : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.REPAY_WAY, outputVo.getRepayWay())); //还款方式
            nlsCreditInfoVO.setApplyRateY(AmtUtil.checkDecimalInfo(outputVo.getLoanIntRate(), oneHundred_100));// 申请执行年利率
            nlsCreditInfoVO.setIsCreInfo(BaseConstant.YES);//是否同意查征信
            nlsCreditInfoVO.setCurrencyType(CurrencyConstant.CNY);// 币种
            nlsCreditInfoVO.setApplyDate(aplDt);// 申请日期
            nlsCreditInfoVO.setChannelNo(chanNo);// 渠道编号
            nlsCreditInfoVO.setIndivMobile(mobile);// 手机号码
            nlsCreditInfoVO.setBdReasonCode(StringUtil.replaceNullByObj(reqCreditBean.getBDRsnCd()));// 百度原因码
            nlsCreditInfoVO.setBdReasonMsg(StringUtil.replaceNullByObj(reqCreditBean.getBDRsnCdRmk()));// 百度原因码说明
            nlsCreditInfoVO.setBdRisCode(reqCreditBean.getBDPolcyCd());// 百度策略码
            nlsCreditInfoVO.setNational(StringUtil.isNullorBank(reqCreditBean.getNation()) ? CountryConstant.CHN : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.COUNTRY, reqCreditBean.getNation()));// 国籍
            nlsCreditInfoVO.setBdIncome(reqCreditBean.getIncmAmtLvl());// 月收入（区间）
            nlsCreditInfoVO.setBdPreCustSeg(reqCreditBean.getBDPreLoanLvl());// 人群分层
            nlsCreditInfoVO.setBdDxmScore(reqCreditBean.getBDAScr());// 度小满a模型分
            nlsCreditInfoVO.setBdHolmesBlackScore(reqCreditBean.getLnkBlckPrdctScr());// 关联黑产分
            nlsCreditInfoVO.setBdHolmesAgentScore(reqCreditBean.getLnkIntrmyScr());//关联中介分
            nlsCreditInfoVO.setBdBlackListType(reqCreditBean.getBlklistTp());// 黑名单类型
            nlsCreditInfoVO.setBdPrcidNormalScoreExp3(reqCreditBean.getBDIdCertScr());// 内部多头分（身份证）
            nlsCreditInfoVO.setBdBidNormalScoreExp3(reqCreditBean.getBDAcctNoScr());// 内部多头分（百度帐号）
            nlsCreditInfoVO.setBdPhoneNormalScoreExp3(reqCreditBean.getBDMblNoScr());// 内部多头分（手机）
            if (StringUtil.isNotEmpty(reqCreditBean.getEqlAmtPrin12Int())) {
                nlsCreditInfoVO.setBdIntIncome12(new BigDecimal(reqCreditBean.getEqlAmtPrin12Int()));// 等额本金12期利息（循环产品）
            }
            // 反洗钱增加字段 2019-07-01
            // 学历
            nlsCreditInfoVO.setEdu(reqCreditBean.getEduCd());
            // 职业
            nlsCreditInfoVO.setProfession(reqCreditBean.getCrrCd() == null ? ""
                    : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.CRR, reqCreditBean.getCrrCd()));// 职业
            // 单位名称
            nlsCreditInfoVO.setWrkCorpNm(reqCreditBean.getWrkCorpNm());
            // 单位地址
            nlsCreditInfoVO.setWrkCorpAddr(reqCreditBean.getWrkCorpAddr());
            // 职称
            nlsCreditInfoVO.setTtl(reqCreditBean.getTtlCd());
            // 证件地址 （户籍地址）
            nlsCreditInfoVO.setCertAddr(reqCreditBean.getCertAddr());
            // 居住地址  （联系地址）
            nlsCreditInfoVO.setIndivRsdAddr(reqCreditBean.getCtcAddr());

            nlsCreditInfoVO.setCreateUser("admin");// 创建人（直接插值）
            nlsCreditInfoVO.setCreateTime(DateUtility.getCurrAppDateTimeString());// 创建时间
            nlsCreditInfoVO.setApprvDate(DateUtility.getCurrDate());// 审批日期
            nlsCreditInfoVO.setApprvSts(MsLoanConstant.NlsApplyStateEnum.APPR.VALUE);// 处理中
            nlsCreditInfoVO.setGlobalSerno(esbReqServiceBean.getSysHead().getGlblSrlNo());// 全局流水号
            nlsCreditInfoVO.setPlatfmid(
                    "".equals(esbReqServiceBean.getSysHead().getPlafmID()) || esbReqServiceBean.getSysHead().getPlafmID() == null ?
                            MsLoanConstant.PlafmEnum.BD.VALUE : esbReqServiceBean.getSysHead().getPlafmID()
            );// 平台ID
            nlsCreditInfoVO.setPlatfmusrid(
                    "".equals(esbReqServiceBean.getSysHead().getPlafmUsrID()) || esbReqServiceBean.getSysHead().getPlafmUsrID() == null ?
                            chanNo + certNo : esbReqServiceBean.getSysHead().getPlafmUsrID()
            );// 平台用户ID
            nlsCreditInfoVO.setSoltStage(PrdAdaptedSoltEnums.SoltStageEnum.CREDIT.getVALUE());//插槽阶段，授信
            // add by ludayong 2019/11/15 【数据权限】增加网贷经办机构赋值
            // 网贷经办机构
            nlsCreditInfoVO.setNlsOperOrgid(InstitutionEnums.InstitutionEnum.GZYHZHYHZXSCTD1.getCode());
            int num1 = nlsCreditInfoService.insertNlsCreditInfo(nlsCreditInfoVO);
            // 插入网贷业务过程表
            NlsProcessBizVO inNlsProcessBizVo = new NlsProcessBizVO();
            inNlsProcessBizVo.setApplySeq(applSeq);// 申请流水号
            inNlsProcessBizVo.setCusId(cusId);// 客户编号
            inNlsProcessBizVo.setCusName(cusName);// 客户名称
            inNlsProcessBizVo.setPrdId(outputVo.getPrdId());// 产品ID
            inNlsProcessBizVo.setPrdCode(prdCde);// 产品代码
            inNlsProcessBizVo.setPrdName(prdName);// 产品名称
            inNlsProcessBizVo.setHangTimes(QueueTaskEnums.QueueHangTimesEnum.INITIALIZE.getTimes());
            inNlsProcessBizVo.setQueueTaskState(QueueTaskEnums.QueueTaskStateEnum.EXECUTORY.getCode());
            inNlsProcessBizVo.setCreateTime(DateUtility.getCurrAppDateTimeString());// 创建时间
            inNlsProcessBizVo.setLastModifyTime(DateUtility.getCurrAppDateTimeString());// 最后修改时间
            inNlsProcessBizVo.setCreateDate(DateUtility.getCurrAppDateStr());// 创建日期
            // add by ludayong 2019/11/15 【数据权限】增加经办机构赋值
            // 经办机构
            inNlsProcessBizVo.setNlsOperOrgid(InstitutionEnums.InstitutionEnum.GZYHZHYHZXSCTD1.getCode());
            int num2 = nlsProcessBizService.insertNlsProcessBiz(inNlsProcessBizVo);

            // 插入Bd征信信息表
            ReqCreditBean.CrdtInfoList crdtInfoList = reqCreditBean.getCrdtInfoList();
            BdZxInfoVO bdZxInfoVO = new BdZxInfoVO();
            int sum3 = setAndInsertBdZxInfo(crdtInfoList, bdZxInfoVO, applSeq );
            // 5.组装返回报文
            if (num1 == -1 || num2 == -1 || sum3 == -1) {
                throw new BizException("插入数据表异常!");
            } else {
                producerService.sendMsg(new Message(TopicEnums.QUEUE_TASK_CREDIT_TOPIC.getTopicId(), TagEnums.TAG_QUEUE_CREDIT_TASK.getTagId(), applSeq, JSON.toJSONString(nlsCreditInfoVO).getBytes("UTF-8")));
                return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
                        JSON.toJSONString(buildRespCreditBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "交易成功")), //
                        EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), //
                        EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), //
                        "交易成功");
            }

        } catch (ESBException e) {
            logger.error("授信申请服务接口处理失败!" + e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), e.getMessage())), //
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
                    e.getMessage());
        } catch (BizException e) {
            logger.error("授信申请服务接口处理失败!" + e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), e.getMessage())), //
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
                    e.getMessage());
        } catch (Exception e) {
            logger.error("授信申请服务接口处理失败!" + e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), e.getMessage())), //
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
                    e.getMessage());
        } finally {
            logger.info("授信申请交易结束----------申请流水号：" + applSeq + "------------全局流水号" + glblSrlNo);
            TraceUtil.clear();
        }
    }

    /**
     * 设置百度征信82个字段: <br>
     * 0.1:caoxin:2019/7/12 11:07: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/7/12 11:07
     * @version 0.1
     * @since 2019/7/12 11:07
     */
    private int setAndInsertBdZxInfo(ReqCreditBean.CrdtInfoList crdtInfoList, BdZxInfoVO bdZxInfoVO, String lmtApplySeq) {
        bdZxInfoVO.setLmtApplySeq(lmtApplySeq);
        bdZxInfoVO.setZxCreditCardAccuDelqCnt(crdtInfoList.getCrdtCardAcmOvdueNum());
        bdZxInfoVO.setZxCreditCardRcyDelqDate(crdtInfoList.getCrdtCardLastestOvdueDt());
        bdZxInfoVO.setZxCreditCardDelqStatus30Dayyues(crdtInfoList.getCrdtCard30DyOvdueSt());
        bdZxInfoVO.setZxCreditCardDelqStatus30to60days(crdtInfoList.getCrdtCard30To60DyOvdueSt());
        bdZxInfoVO.setZxCreditCardDelqStatus60to90days(crdtInfoList.getCrdtCard61To90DyOvdueSt());
        bdZxInfoVO.setZxCreditCardDelqStatus90to180days(crdtInfoList.getCrdtCard90To180DyOvdueSt());
        bdZxInfoVO.setZxCreditCardDelqStatus6to12months(crdtInfoList.getCrdtCard6To12MnthOvdueSt());
        bdZxInfoVO.setZxCreditCardDelqStatus24months(crdtInfoList.getCrdtCard24MnthOvdueSt());
        bdZxInfoVO.setZxCreditCardRcyUpdateDate(crdtInfoList.getCrdtCardRcrdLastestUdtDt());
        bdZxInfoVO.setZxHouseFundMonthShouldPayAmt(String.valueOf(crdtInfoList.getMnthlyHsPblcFndLoanRpyAmt()));
        bdZxInfoVO.setZxLoanRcyDelqDate(crdtInfoList.getLoanLastOvdueDt());
        bdZxInfoVO.setZxLoanDelqStatus30dayyues(crdtInfoList.getLoanOvdueIn30DySt());
        bdZxInfoVO.setZxLoanDelqStatus30to60days(crdtInfoList.getLoanOvdue31To60DySt());
        bdZxInfoVO.setZxLoanDelqStatus60to90days(crdtInfoList.getLoanOvdue61To90DySt());
        bdZxInfoVO.setZxLoanDelqStatus90to180days(crdtInfoList.getLoanOvdue91To180DySt());
        bdZxInfoVO.setZxLoanDelqStatus6to12months(crdtInfoList.getLoanOvdueOvr180DySt());
        bdZxInfoVO.setZxLoanRcyUpdateDate(crdtInfoList.getLoanRcrdLastestUdtDt());
        bdZxInfoVO.setZxRcyQueryDate(crdtInfoList.getQryRqsTmLastPBOCQryDt());
        bdZxInfoVO.setZxWarrantLoanTypeUnnormal(crdtInfoList.getGnrPymtNum());
        bdZxInfoVO.setZxFirstLoanDate(crdtInfoList.getFrstLoanDistrDt());
        bdZxInfoVO.setZxFirstCreCardDate(crdtInfoList.getFrstCrCardDistrDt());
        bdZxInfoVO.setZxRcy6MLoanQueryCnt(crdtInfoList.getLoanAprvlQryIn6MnthLoanNum());
        bdZxInfoVO.setZxRcy6MLoanQueryCompanyCnt(crdtInfoList.getLoanAprvlLt6MosQryAgncNum());
        bdZxInfoVO.setZxRcy6MCreCardQueryCompanyCnt(crdtInfoList.getCrdtCardA6MosQryAgncNum());
        bdZxInfoVO.setZxRcy6MCreCardQueryCnt(crdtInfoList.getCrdtCardAprvlQry6MnthNum());
        bdZxInfoVO.setZxRcy1MLoanQueryCnt(crdtInfoList.getLoanAprvlQryInRecntMnthNum());
        bdZxInfoVO.setZxRcy1MLoanQueryCompanyCnt(crdtInfoList.getLoanAprvlLMnthQryAgncNum());
        bdZxInfoVO.setZxRcy1MCreCardQueryCompanyCnt(crdtInfoList.getCrdtCardAprvlMoQryAgncNum());
        bdZxInfoVO.setZxRcy1MCreCardQueryCnt(crdtInfoList.getCrdtCardAprvlQryMnthNum());
        bdZxInfoVO.setZxRcy3MLoanQueryCompanyCnt(crdtInfoList.getLoanAprvlQryR3MnthAgncNum());
        bdZxInfoVO.setZxRcy3MLoanQueryCnt(crdtInfoList.getLoanAprvlQryRecnt3MnthNum());
        bdZxInfoVO.setZxRcy3MCreCardQueryCompanyCnt(crdtInfoList.getCrdtCardAprvlQry3MoAgncNum());
        bdZxInfoVO.setZxRcy3MCreCardQueryCnt(crdtInfoList.getCrdtCardAprvlQry3MnthNum());
        bdZxInfoVO.setZxAccountCnt(crdtInfoList.getUnregsdAcctCrdtCardNum());
        bdZxInfoVO.setZxTotalCreditAmt(String.valueOf(crdtInfoList.getUncnclAcctCrdtCardAuthLmt()));
        bdZxInfoVO.setZx1MthDelqMaxAmt(String.valueOf(crdtInfoList.getMxMnthlyOvdueLoanAmt()));
        bdZxInfoVO.setZxMaxMonths(crdtInfoList.getMxOvdueLoanMos());
        bdZxInfoVO.setZxBadBebtsBalance(crdtInfoList.getBalBdDbtSumrInf());
        bdZxInfoVO.setZxBadBebtsCnt(crdtInfoList.getNumBdDbtSumyInf());
        bdZxInfoVO.setZxCreditRetCode(crdtInfoList.getQryStCd());
        bdZxInfoVO.setZxIssuBankCnt(crdtInfoList.getUncnclAcctCrdtCardIssOCnt());
        bdZxInfoVO.setZxUseCreditAmt(crdtInfoList.getUncnclAcctCrdtCardUsedLmt());
        bdZxInfoVO.setZxCreditBal(String.valueOf(crdtInfoList.getActvCrdtCardUsedLmt()));
        bdZxInfoVO.setZxRcy6MAvgUseCreditAmt(String.valueOf(crdtInfoList.getUncnclAcctCrdtCard6MoAvLmt()));
        bdZxInfoVO.setZxCreditAvgLimit(String.valueOf(crdtInfoList.getCrdtCardAvLmt()));
        bdZxInfoVO.setZxCreCardUseCreditRate(String.valueOf(crdtInfoList.getCrdtCardLmtUtlzRt()));
        bdZxInfoVO.setZxMaxCreditAmt(String.valueOf(crdtInfoList.getUncnclAcctCrCardMxCrdtLmt()));
        bdZxInfoVO.setZxMinCreditAmt(String.valueOf(crdtInfoList.getUncnclAcctCrCardMinCrdtLmt()));
        bdZxInfoVO.setZxCreCardStatus1(crdtInfoList.getCrdtCardQscrdtCrnAcctSt());
        bdZxInfoVO.setZxCreCardAcctNowTotalDelqAmt(String.valueOf(crdtInfoList.getCrCardAcctCurrTotOvdueAmt()));
        bdZxInfoVO.setZxCreCardDelqMaxAmt(String.valueOf(crdtInfoList.getMxMnthlyOvdueCrdtCardAmt()));
        bdZxInfoVO.setZxCreCardMaxMonthsCnt(crdtInfoList.getCrdtCardMxOvdueMos());
        bdZxInfoVO.setZxCreCardDelqAccoutCnt(crdtInfoList.getCrdtCardOvdueAcctCnt());
        bdZxInfoVO.setZxRcy12MCreCardMaxDelqPeriod(crdtInfoList.getCrdtCardAcct12MosOvdueTerm());
        bdZxInfoVO.setZxRcy24MCreCardMaxDelqPeriod(crdtInfoList.getCrdtCardAcct24MosOvdueTerm());
        bdZxInfoVO.setZxRcy6MCreCardMaxDelqPeriod(crdtInfoList.getCrdtCardAcct6MosOvdueTerm());
        bdZxInfoVO.setZxLoanBalCnt(crdtInfoList.getUncldLoanCnt());
        bdZxInfoVO.setZxCommerHouseLoanBlance(String.valueOf(crdtInfoList.getIndvCmrclHsngLoanUncldBal()));
        bdZxInfoVO.setZxPersonalLoanCnt(String.valueOf(crdtInfoList.getPrsnlOprlLoanUncldLoanCnt()));
        bdZxInfoVO.setZxLoanCompanyBalCnt(crdtInfoList.getUncldLoanOrgCnt());
        bdZxInfoVO.setZxLoanBalanceAmt(String.valueOf(crdtInfoList.getUncldLoanBal_1()));
        bdZxInfoVO.setZxCreCardStatus3(crdtInfoList.getLoanCrnAcctSt());
        bdZxInfoVO.setZxBlanceShouldPayAmt(String.valueOf(crdtInfoList.getUncldLoanMnthRpmtDueMoAmt()));
        bdZxInfoVO.setZxCreCardStatus4(crdtInfoList.getLoanCrnLvl5ClSt());
        bdZxInfoVO.setZxCreCardNowShouldPayAmt(String.valueOf(crdtInfoList.getCrdtCardThsMoTotAmt()));
        bdZxInfoVO.setZxHouseLoan1MAvgPayAmt(String.valueOf(crdtInfoList.getIndvHsPblcFndLoanLastRAmt()));
        bdZxInfoVO.setZxAccountNowTotalDelqAmt(String.valueOf(crdtInfoList.getLoanAcctCurrOvdueAmt()));
        bdZxInfoVO.setZxDelqCnt(crdtInfoList.getLoanOvdueCnt());
        bdZxInfoVO.setZxWarrantLoanCnt(crdtInfoList.getGuarCnt());
        bdZxInfoVO.setZxWarrantLoanType(crdtInfoList.getGuarLoanCrnLvl5ClSt());
        bdZxInfoVO.setZxRcy6MAvgPayAmt(String.valueOf(crdtInfoList.getUncldLoanRecnt6MnthAvRAmt()));
        bdZxInfoVO.setZxFirstLoanMonth(crdtInfoList.getFrstDistrMnth());
        bdZxInfoVO.setZxMaxUpdated(crdtInfoList.getCrrInfInfLastestUdtDt());
        bdZxInfoVO.setZxRestDisposalCnt(crdtInfoList.getAstDispCntSumyInf());
        bdZxInfoVO.setZxCreCardStatus5(crdtInfoList.getLoanSpclTxnTpSt());
        bdZxInfoVO.setZxHouseFundMonthPayAmt(String.valueOf(crdtInfoList.getHsPblcFndLoanMoPyAmt()));
        bdZxInfoVO.setZxHouseFundPayLastMonth(crdtInfoList.getHsPblcFndLoanPymtToMo());
        bdZxInfoVO.setZxHouseFundPayStatus(crdtInfoList.getHsPblcPySt());
        bdZxInfoVO.setZxHouseFundSelfRate(crdtInfoList.getHsPblcIdvPayRto());
        bdZxInfoVO.setZxHouseFundCompanyRate(crdtInfoList.getHsPblcCorpPayRto());
        bdZxInfoVO.setZxHouseFundRecordUpdate(crdtInfoList.getHsPblcFndInfLastestUdtDt());
        bdZxInfoVO.setZxCreCardStatus2(crdtInfoList.getCrdtCardQscrdtSpclTxnTpSt());
        bdZxInfoVO.setCreateTime(new Date());
        bdZxInfoVO.setCreateUser("admin");
        bdZxInfoVO.setUpdateTime(new Date());
        bdZxInfoVO.setUpdateUser("admin");
        return bdZxInfoService.insertBdZxInfo(bdZxInfoVO);
    }

    /**
     * 组织用户借款请求接口的返回对象
     *
     * @param retStCd 返回状态码
     * @param rtnMsg  返回信息
     * @return
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午1:59:46
     */
    private RespCreditBean buildRespCreditBean(String retCd, String retMsg) {
        RespCreditBean respCreditBean = new RespCreditBean();
        respCreditBean.setRetCd(retCd);
        respCreditBean.setRetMsg(retMsg);
        return respCreditBean;
    }

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;
    @Autowired
    @Qualifier("nlsProcessBizService")
    private NlsProcessBizService nlsProcessBizService;
    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;
    @Autowired
    @Qualifier("prdInfoService")
    private PrdInfoService prdInfoService;
    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;
    @Autowired
    @Qualifier("bdZxInfoService")
    private BdZxInfoService bdZxInfoService;
}
